package com.mfoyou.agent.web.service.order;

import com.alibaba.fastjson.JSON;
import com.mfoyou.agent.web.service.common.GeoService;
import com.mfoyou.agent.web.service.thirdPart.XGPushSerivce;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;
import org.mfoyou.agent.common.dao.domain.HuawuIdcardInfo;
import org.mfoyou.agent.common.dao.domain.HuawuServiceOrder;
import org.mfoyou.agent.common.dao.domain.HuawuWorker;
import org.mfoyou.agent.common.entity.MfoyouWorkStatistics;
import org.mfoyou.agent.common.entity.enums.OrderState;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.common.inf.IOrder;
import org.mfoyou.agent.common.inf.IStatistics;
import org.mfoyou.agent.utils.common.DateUtils;
import org.mfoyou.agent.utils.common.GisUtils;
import org.mfoyou.agent.utils.common.RunerWorkState;
import org.mfoyou.agent.utils.common.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.GeoRadiusResponse;

import java.util.*;

/**
 * 订单跑腿服务类
 *
 * @author hzhang7
 */
@Service
public class OrderRunnerService {

    private static Logger logger = LoggerFactory.getLogger(OrderRunnerService.class);

    @Autowired
    RedisCacheManger redisCacheManger;
    @Autowired
    GeoService geoService;
    @Autowired
    IStatistics iStatistics;
    @Autowired
    IOrder iOrder;
    @Autowired
    XGPushSerivce xgPushSerivce;
    @Autowired
    PaymentService paymentService;
    @Autowired
    IIdentity iIdentity;
    @Autowired
    IAccount iAccount;

    /**
     * 插入并找寻代理商跑腿儿小哥
     *
     * @param orderId   订单id
     * @return
     */
    public Boolean insertSeekAgentRunner(Integer orderId) {
        //多余的 获取  重复查询了数据库
        HuawuServiceOrder mfoyouServiceOrder = iOrder.getServiceOrderInfo(orderId);
        logger.info(String.format("OrderRunnerService.insertSeekAgentRunner 订单详情=[%s]", JSON.toJSONString(mfoyouServiceOrder)));
        // 代理商id
        Integer agentId = mfoyouServiceOrder.getAgentId();
        // 站长id
        Integer stationId = mfoyouServiceOrder.getStationId();
        List<Integer> userIdInstation = null;
        if (stationId != null) {
            userIdInstation = iIdentity.getWorkerInStation(stationId);
        }
        if (userIdInstation != null && userIdInstation.size() == 0) {
            return false;
        }

        Double posLat = mfoyouServiceOrder.getServiceUserLat();
        Double posLon = mfoyouServiceOrder.getServiceUserLon();
        // 地理位置列表: 以 posLat posLon 为经纬度的点为圆心获取三公里以内的跑腿小哥
        List<GeoRadiusResponse> list = null;
        if (posLat != null && posLon != null) {

            // 获取30公里范围内的跑腿小哥列表
            list = geoService.getRunner(agentId, posLon, posLat, 30000);
            logger.info(String.format("经纬度不为空-获取30公里范围内的跑腿儿小哥列表: 订单id=[%s], 经度=[%s], 纬度=[%s],小哥列表=[%s]", orderId,posLon, posLon, JSON.toJSONString(list)));
            // 在指定位置添加订单
            geoService.addOrderPos(posLon, posLat, "" + orderId);
            // 如果范围内没有跑腿小哥,获取300公里范围内的小腿小哥
            if (list == null || list.size() == 0) {
                list = geoService.getRunner(agentId, posLon, posLat, 300000);
                logger.info(String.format("获取300公里范围内的跑腿儿小哥列表: 订单id=[%s], 经度=[%s], 纬度=[%s], 小哥列表=[%s]", orderId, posLon, posLat, JSON.toJSONString(list)));
            }
        }
        Integer userType = 1;
        // 跑腿小哥列表
        List<String> userIds = new ArrayList<>();
        if (list == null || list.size() == 0) {
            if (agentId != null && agentId != 0) {
                if (userIds.size() == 0) {
                    userType = 2;
                    if (agentId < 10) {
                        userIds.add("0" + agentId);
                        userIds.add("0" + stationId);
                        logger.info(String.format("agentId < 10 添加推送给 代理商=[%s]和站长=[%s] userId=[%s]", agentId, stationId, JSON.toJSONString(userIds)));
                    } else {
                        userIds.add("" + agentId);
                        userIds.add("" + stationId);
                        logger.info(String.format("agentId >= 10 添加推送给 代理商=[%s]和站长=[%s] userId=[%s]", agentId, stationId, JSON.toJSONString(userIds)));
                    }
                }
            } else {
                return false;
            }
        } else {
            for (GeoRadiusResponse geoRadiusResponse : list) {
                String userId = GeoService.runner_getUserId(geoRadiusResponse.getMemberByString());
                if (userIdInstation != null && userId != null && !userIdInstation.contains(Integer.valueOf(userId))) {
                    continue;
                }
                if (userId.length() < 2) {
                    userId = "0" + userId;
                }
                userIds.add(userId);
            }
            logger.info(String.format("获取的指定范围的跑腿小哥列表=[%s]", JSON.toJSONString(userIds)));
            //代理商区域需要进行二次推送
            if (agentId != 0) {
                logger.info("备选如果3分钟后无人接单推送团队管理员和30公里范围内所有人员");
                //备选如果3分钟后无人接单推送团队管理员和30公里范围内所有人员
                xgPushSerivce.pushNoticeNewOrderAgentCheck(agentId, orderId, userType, userType, System.currentTimeMillis() + 2 * 60 * 1000L);
                List<GeoRadiusResponse> list0 = geoService.getRunner(agentId, posLon, posLat, 30000);
                if (list0 == null || list0.size() == 0) {
                    logger.info("30公里范围内跑腿小哥为0");
                } else {
                    List<String> userIds0 = new ArrayList<>();
                    String agents = "" + agentId;
                    if (agents.length() < 2) {
                        agents = "0" + agents;
                    }
                    userIds0.add(agents);
                    for (GeoRadiusResponse geoRadiusResponse : list0) {
                        String userId = GeoService.runner_getUserId(geoRadiusResponse.getMemberByString());
                        if (userIdInstation != null && userId != null && !userIdInstation.contains(userId)) {
                            continue;
                        }
                        if (userId.length() < 2) {
                            userId = "0" + userId;
                        }
                        userIds0.add(userId);
                    }
                    if (userIds0.size() > 0) {
                        logger.info("推送团队管理员和30公里范围内所有人员 method: xgPushSerivce.pushNoticeNewOrderCheck");
                        xgPushSerivce.pushNoticeNewOrderCheck(userIds0, orderId, userType, userType, System.currentTimeMillis() + 3 * 60 * 1000L);
                    }
                }
            }
        }
        if (userIds.size() > 0) {
            logger.info(String.format("调用信鸽附推送订单提醒给跑腿小哥 userIds=[%s]", JSON.toJSONString(userIds)));
            xgPushSerivce.pushNoticeNewOrderToRuner(userIds, orderId, userType, userType, System.currentTimeMillis());
            if (userType == 2) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 为订单匹配跑腿小哥
     *
     * @param mfoyouServiceOrder
     * @param ownUserId
     * @return
     */
    public List<RunerWorkState> orderMatchAgentRunner(HuawuServiceOrder mfoyouServiceOrder, Integer ownUserId) {
        Integer agentId = mfoyouServiceOrder.getAgentId();
        Double srcLat = mfoyouServiceOrder.getServiceOrderPickupAddressLat();
        Double srcLon = mfoyouServiceOrder.getServiceOrderPickupAddressLon();
        Double desLat = mfoyouServiceOrder.getServiceOrderDeliveryAddressLat();
        Double desLon = mfoyouServiceOrder.getServiceOrderDeliveryAddressLon();
        Double uLat = mfoyouServiceOrder.getServiceUserLat();
        Double uLon = mfoyouServiceOrder.getServiceUserLon();
        if (agentId == null || agentId == 0) {
            return new ArrayList<>();
        }
        List<GeoRadiusResponse> list = null;
        if (desLat != null && desLon != null) {
            list = geoService.getRunner(agentId, desLon, desLat, 50000);
        }
        if (list != null && list.size() == 0 && srcLat != null && srcLon != null) {
            list = geoService.getRunner(agentId, srcLon, srcLat, 50000);
        }
        if (list != null && list.size() == 0 && uLat != null && uLon != null) {
            list = geoService.getRunner(agentId, uLon, uLat, 50000);
        }
        List<Integer> userIds = new ArrayList<>();
        Map<Integer, RunerWorkState> map = new HashMap<>();
        List<HuawuWorker> mfoyouUsers;
        if (list == null || list.size() == 0) {
            if (ownUserId == null) {
                mfoyouUsers = iIdentity.getMfoyouWorkerListByAgentId(mfoyouServiceOrder.getAgentId(), mfoyouServiceOrder.getStationId());
            } else {
                mfoyouUsers = iIdentity.getMfoyouWorkerListByAgentIdExcept(mfoyouServiceOrder.getAgentId(), ownUserId, mfoyouServiceOrder.getStationId());
            }
            for (HuawuWorker huawuWorker : mfoyouUsers) {
                userIds.add(huawuWorker.getUserId());
                RunerWorkState runerWorkState = new RunerWorkState();
                runerWorkState.setUserId(huawuWorker.getUserId());
                runerWorkState.setLat(huawuWorker.getWorkerLat());
                runerWorkState.setLon(huawuWorker.getWorkerLong());
                if (huawuWorker.getWorkerLat() != null && huawuWorker.getWorkerLong() != null && srcLon != null && srcLat != null) {
                    runerWorkState.setDistane((int) GisUtils.getDistance(srcLon, srcLat, huawuWorker.getWorkerLong(), huawuWorker.getWorkerLat()));
                }
                map.put(huawuWorker.getUserId(), runerWorkState);
            }
        } else {
            for (GeoRadiusResponse geoRadiusResponse : list) {
                Integer userId = StrUtil.parseInteger(GeoService.runner_getUserId(geoRadiusResponse.getMemberByString()));
                RunerWorkState runerWorkState = new RunerWorkState();
                runerWorkState.setDistane((int) geoRadiusResponse.getDistance());
                runerWorkState.setLat(geoRadiusResponse.getCoordinate().getLatitude());
                runerWorkState.setLon(geoRadiusResponse.getCoordinate().getLongitude());
                if (ownUserId == null || ownUserId.intValue() != userId.intValue()) {
                    userIds.add(userId);
                    runerWorkState.setUserId(userId);
                    map.put(userId, runerWorkState);
                }
            }
            mfoyouUsers = iIdentity.getMfoyouWorkerList(userIds, mfoyouServiceOrder.getStationId());
        }
        List<Integer> listState = new ArrayList<>();
        listState.add(OrderState.emRunerAccept.getValue());
        listState.add(OrderState.emServiceFinshPick.getValue());
        listState.add(OrderState.emServiceStart.getValue());
        Map<Integer, Integer> MfoyouServiceOrder = iOrder.getWorkerOrder(userIds, listState, null, null);
        HashMap<Integer, MfoyouWorkStatistics> hashMap = new HashMap<>();
        if (mfoyouServiceOrder.getServiceOrderSource() == -2) {
            List<MfoyouWorkStatistics> today = paymentService.getUsersWorkeWallet(userIds, DateUtils.getTimesmorning(), null);
            for (MfoyouWorkStatistics mfoyouWorkStatistics : today) {
                hashMap.put(mfoyouWorkStatistics.getUserId(), mfoyouWorkStatistics);
            }
        }
        for (HuawuWorker mfoyouUser : mfoyouUsers) {
            RunerWorkState runerWorkState = map.get(mfoyouUser.getUserId());
            if (mfoyouServiceOrder.getServiceOrderSource() == -2) {
                MfoyouWorkStatistics mfoyouWorkStatistics = hashMap.get(mfoyouUser.getUserId());
                if (mfoyouWorkStatistics != null) {
                    runerWorkState.setTodayAmount(mfoyouWorkStatistics.getOrderAoument());
                    runerWorkState.setTodayOrderCount(mfoyouWorkStatistics.getOrderCount());
                }
            }
            //标识
            runerWorkState.setNickName("test");
            HuawuIdcardInfo idcardInfo = iAccount.getIdcardInfo(mfoyouUser.getUserId());
            if (idcardInfo != null) {
                runerWorkState.setName(idcardInfo.getUserTrueName());
            }
            runerWorkState.setOpenState(mfoyouUser.getWorkerOpenState());
            runerWorkState.setPhone(mfoyouUser.getWorkerPhone());
            runerWorkState.setHeadUrl(redisCacheManger.hget("u:" + mfoyouUser.getUserId(), "userHeadUrl"));
            runerWorkState.setStar(mfoyouUser.getWorkerStar());
            runerWorkState.setRemainderOrderCount(MfoyouServiceOrder.get(runerWorkState.getUserId()));
            if (runerWorkState.getRemainderOrderCount() == null) {
                runerWorkState.setRemainderOrderCount(0);
            }
        }
        List<RunerWorkState> listRet = new ArrayList<>();
        map.values().removeIf(t -> t.getNickName() == null);
        listRet.addAll(map.values());
        Collections.sort(listRet);
        return listRet;
    }

}
